<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Backend\BaseController;


use App\Services\Company\Models\CompanyCategory;
use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\VideoRequest;

use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Interfaces\VideoServiceInterface;

use App\Services\Business\Models\Video;
use App\Services\Business\Services\VideoService;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Services\UserService;
use App\Services\Order\Interfaces\OrderServiceInterface;
use App\Services\Order\Services\OrderService;




use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;


class VideoController extends BaseController
{







    /**
     * @var VideoService
     */
    protected $videoService;
    /**
     * @var ConfigService
     */
    protected $configService;

    /**
     * @var UserService
     */
    protected $userService;


    /**
     * @var BusinessState
     */
    protected $businessState;
    /**
     * @var OrderService
     */
    protected $orderService;






    public function __construct(

        ConfigServiceInterface       $configService,
        UserServiceInterface         $userService,
        BusinessState                $businessState,
        OrderServiceInterface        $orderService,
        VideoServiceInterface  $videoService


    )
    {


        $this->userService = $userService;
        $this->configService = $configService;
        $this->businessState = $businessState;
        $this->orderService = $orderService;
        $this->videoService  = $videoService;

    }


    public
    function index(Request $request)
    {

        $companyId = $this->check() ? $this->loginCompanyId() : $request->input('company_id');
        $categoryId = $request->input('cid');
        $userIds = $request->input('user_ids');
        $keywords = $request->input('keywords');
        $sort = $request->input('sort', 'id');
        $courseId = $request->input('course_id', 0);
        $order = $request->input('order', 'desc');
        $excludeVideoIds = $request->input('exclude_ids', []);
        $currentVideoId = $request->input('current_video_id');


        $videos = Video::query()
            ->with(['user', 'tags'])
            ->where('is_show', 1)
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = CompanyCategory::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('my_category_id', $ids);
            })
            ->when($courseId, function ($query) use ($courseId) {
                $query->where('course_id', $courseId);
            })
            ->when($userIds, function ($query) use ($userIds) {
                return $query->whereIn('user_id', $userIds);
            })
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($currentVideoId, function ($query) use ($currentVideoId, $excludeVideoIds) {
                //这里排除父id,当前编辑的id，还有已经
                $mappingVideoIds = $this->videoService->getVideoMappingIds($currentVideoId);
                $videoIds = array_merge($mappingVideoIds, $excludeVideoIds, [$currentVideoId]);
                $query->whereNotIn('id', $videoIds);
            })
            ->where('company_id', $companyId)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));
        return $this->successData(compact('videos'));
    }


    /**
     * 视频新增
     * @param VideoRequest $request
     * @param Video $video
     * @return JsonResponse
     */
    public
    function store(VideoRequest $request, Video $video)
    {

        $data = $request->filldata();
        $video->fill($data)->save($data);
        return $this->successData(compact('video'));
    }



    /**
     * 更新标题
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public
    function updateTitle(Request $request, $id)
    {
        $title = $request->input('title');
        $video = Video::query()->where('id', $id)->firstOrFail();
        $video->update(['title' => $title]);
        return $this->success(__('标题更新成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function updateThumb(Request $request, $id): JsonResponse
    {
        $thumb = $request->input('thumb');
        $article = Video::query()->where('id', $id)->firstOrFail();
        $article->update(['thumb' => $thumb]);
        return $this->success(__('封面更新成功'));
    }





    public
    function show(Request $request, $id)
    {
        $video = Video::query()->where('id', $id)->firstOrFail();
        $result = empty($video->getAttribute('is_show')) ? 1 : 0;
        $video->update(['is_show' => $result]);
        return $this->successData(__('操作成功'));

    }


    /**
     * 删除视频
     * @param Video $video
     * @param ConfigServiceInterface $configService
     * @param VideoServiceInterface $videoService
     * @return JsonResponse
     */
    public
    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {


        $video = Video::find($id);
        DB::transaction(function () use ($video, $configService, $videoService) {

            //删除阿里云的附件
            $videoService->deleteVideo($video['aliyun_video_id'], $configService);

            $video->delete();


        });
        return $this->success(__('删除视频成功'));

    }













}
